package cn.agilean.test.service;

import cn.agilean.test.entity.Company;
import cn.agilean.test.entity.Relation;
import cn.agilean.test.repo.CompanyRepo;
import cn.agilean.test.vo.CompanyVo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class CompanyManager {
    private CompanyRepo companyRepo;

    public CompanyManager(CompanyRepo companyRepo) {
        this.companyRepo = companyRepo;
    }

    public List<CompanyVo> findAll() {
        List<CompanyVo> companyVoList = new ArrayList<>();
        for (Company company : companyRepo.getCompanies()) {
            CompanyVo companyVo = new CompanyVo();
            companyVo.setId(company.getId());
            companyVo.setName(company.getName());
            CompanyVo parentCompany = getParentCompany(company.getId());
            if (parentCompany!= null) {
                companyVo.setParent(parentCompany);
            }
            companyVoList.add(companyVo);
        }
        return companyVoList;
    }

    /**
     *根据公司编码获取公司信息
     */

    public Company getConmanyInfoByCompanyId(String companyId) {
        for (Company company : companyRepo.getCompanies()) {
            if (company.getId().equals(companyId)) {
                return company;
            }
        }
        return null;
    }


    /**
     * 根据公司代码获取上级公司代码
     *
     * @param companyId
     * @return
     */
    public CompanyVo getParentCompany(String companyId) {
        for (Relation relationShip : companyRepo.getRelationShips()) {
            if (relationShip.getCompanyId().equals(companyId)) {
                Company parentCompany = getConmanyInfoByCompanyId(relationShip.getParentId());
                CompanyVo companyVo = new CompanyVo();
                companyVo.setId(parentCompany.getId());
                companyVo.setName(parentCompany.getName());
                return companyVo;
            }
        }
        return null;
    }
}
